#!/usr/bin/env python3
import os
import re
import sys

def main():
    script_dir = os.path.dirname(os.path.abspath(__file__))

    html_path = os.path.join(script_dir, "ghost_site.html")
    output_path = os.path.join(script_dir, "../../include/managers/ghost_esp_site.h")

    os.makedirs(os.path.dirname(output_path), exist_ok=True)

    try:
        with open(html_path, 'r', encoding='utf-8') as f:
            html_content = f.read()
    except Exception as e:
        print(f"Error reading HTML file: {e}")
        sys.exit(1)

    print(f"Original HTML size: {len(html_content)} bytes")

    # Step 1: Remove HTML comments only (no further minification)
    html_content = re.sub(r'<!--[\s\S]*?-->', '', html_content)

    # No CSS or JS minification, no lxml processing
    print(f"Processed HTML size: {len(html_content)} bytes")

    # Convert to binary with null terminator
    minified_binary = html_content.encode('utf-8') + b'\0'
    actual_size = len(minified_binary) - 1  # Exclude null terminator for array size

    bytes_array = [f"0x{b:02X}" for b in minified_binary]

    bytes_per_line = 20
    lines = []
    for i in range(0, len(bytes_array), bytes_per_line):
        chunk = bytes_array[i:i+bytes_per_line]
        lines.append("  " + ", ".join(chunk) + ",")

    if lines:
        lines[-1] = lines[-1][:-1]

    # Use actual size dynamically in the header
    header_content = f"""/* Generated by html_to_header.py, do not edit manually */

/* Contents of file ghost_site.html */
const long int ghost_site_html_size = {actual_size}UL + 1;
const unsigned char ghost_site_html[{actual_size}UL + 1] = {{
{os.linesep.join(lines)}
}};
"""

    try:
        with open(output_path, 'w', encoding='utf-8') as f:
            f.write(header_content)
        print(f"Successfully generated header file: {output_path}")
        print(f"Final size: {actual_size} bytes (plus null terminator)")
        percentage = (1 - (len(minified_binary) / len(html_content.encode('utf-8')))) * 100
        print(f"Size reduction: {percentage:.2f}% (due to comment removal only)")
    except Exception as e:
        print(f"Error writing header file: {e}")
        sys.exit(1)

def install_dependencies():
    import subprocess

    dependencies = []  # No dependencies needed since we're not using lxml or csscompressor

    try:
        for dep in dependencies:
            print(f"Installing {dep}...")
            subprocess.check_call(
                [sys.executable, "-m", "pip", "install", dep]
            )
        print("No dependencies required or installed successfully!")
    except subprocess.CalledProcessError as e:
        print(f"Error installing dependencies: {e}")
        print("No manual installation needed for this script.")
        sys.exit(1)

if __name__ == "__main__":
    main()
